package zhttp

import (
    "context"
    "net/http"
)

type HandlerFunc func(context.Context, http.ResponseWriter, *http.Request)

// Route 路由
type Route struct {
    Method  string
    Path    string
    Handler http.HandlerFunc
}

// Router 路由器
type Router struct {
    routes map[string]map[string]http.HandlerFunc
}

// NewRoute 实例路由
func NewRoute(method, path string, fun http.HandlerFunc) Route {
    return Route{
        Method:  method,
        Path:    path,
        Handler: fun,
    }
}

// AddRouter 添加路由
func (h *Http) AddRouter(routes []Route) {
    for _, route := range routes {
        h.router.HandleFunc(route.Method, route.Path, route.Handler)
    }
}

// AddMiddlewareRoute 添加中间件路由
func (h *Http) AddMiddlewareRoute(middlewares []Middleware, routes []Route) {
    h.AddRouter(MiddlewareRoutes(middlewares, routes))
}

// ServeHTTP 实现Handler接口，匹配方法以及路径
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    if h, ok := r.routes[req.Method][req.URL.Path]; ok {
        h(w, req)
    } else {
        OutputJson(w, 404, "not fount", nil)
    }
}

// HandleFunc 根据方法、路径将方法注册到路由
func (r *Router) HandleFunc(method, path string, f http.HandlerFunc) {
    if r.routes == nil {
        r.routes = make(map[string]map[string]http.HandlerFunc)
    }
    if r.routes[method] == nil {
        r.routes[method] = make(map[string]http.HandlerFunc)
    }
    r.routes[method][path] = f
}